package com.xgkj.diyiketang.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.FaRiZhiActivity;
import com.xgkj.diyiketang.activity.PengYouQuanDetailActivity;
import com.xgkj.diyiketang.activity.data.PengYouQuanAdapter;
import com.xgkj.diyiketang.data.PengYouQuanInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.PengYouQuanListTask;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.MyCustomListView;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.weidget.NoScrollGridView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/6/23.
 */
public class Fragment_QuanZi extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {
    private Context mContext;
    private MyCustomListView mGridView;
    private PengYouQuanAdapter mAdapter;
    private RelativeLayout mTopLayout;
    private ImageView mFaRiJi;
    private MyScrollView mScrollView;
    private int currentPage = 1;
    private int size = 10;
    private int anchorListTaskId = -1;
    private List<PengYouQuanInfo> mList = new ArrayList<PengYouQuanInfo>();
    private ImageView mUserLogo;
    private TextView mUserNick;
    private boolean isShow;

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_xiaoyuan, null);
        mContext = getActivity();
        isShow = true;
        initView(view);
        return view;
    }

    private void initView(View view) {
        mTopLayout = (RelativeLayout) view.findViewById(R.id.toplayout);
        mTopLayout.setFocusable(true);
        mTopLayout.setFocusableInTouchMode(true);
        mTopLayout.requestFocus();
        mGridView = (MyCustomListView) view.findViewById(R.id.pengyouquan_list);
        mAdapter = new PengYouQuanAdapter(mContext);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent detailIntent = new Intent(mContext, PengYouQuanDetailActivity.class);
                detailIntent.putExtra("INFO", (PengYouQuanInfo) mAdapter.getItem(position));
                startActivity(detailIntent);
            }
        });
        mFaRiJi = (ImageView) view.findViewById(R.id.fariji);
        mFaRiJi.setOnClickListener(this);
        mUserLogo = (ImageView) view.findViewById(R.id.head_img);
        mUserNick = (TextView) view.findViewById(R.id.nickname);

        String headImgUrl = EatShowApp.getInstance().getmUserInfo().getUserLogo();
        if (headImgUrl != null && headImgUrl.length() > 0) {
            ViewUtil.Size size = ViewUtil.getHeadImageSize_40(mContext);
            Bitmap cacheBitmap = ImageCache.getInstance(mContext).getBitmapFromMemoryCache(ImageCache.getInstance(mContext).getCacheKey(headImgUrl, size));
            if (cacheBitmap != null) {
                mUserLogo.setImageBitmap(cacheBitmap);
            } else {
                mUserLogo.setImageResource(R.drawable.default_head_image);
                ImageCache.getInstance(mContext).loadBitmapToView(mUserLogo, headImgUrl, size);
            }

        } else {
            mUserLogo.setImageResource(R.drawable.default_head_image);
        }

        String nick = EatShowApp.getInstance().getmUserInfo().getNickName();
        if (nick != null) {
            try {
                mUserNick.setText(URLDecoder.decode(nick, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        mScrollView = (MyScrollView) view.findViewById(R.id.scrollView);
        mScrollView.setOnScrollListener(this);
        getData();
    }

    private void getData() {
        if (currentPage == 0) {
            mGridView.setNoNextPage();
//            Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            return;
        }
        if (anchorListTaskId != -1) {
            return;
        }
        PengYouQuanListTask task = new PengYouQuanListTask(size, currentPage);
        task.addListener(anchorListListener);
        anchorListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fariji:
                Intent fintent = new Intent(mContext, FaRiZhiActivity.class);
                startActivity(fintent);
                break;

        }
    }

    @Override
    public void onScroll() {
        getData();
    }

    private TaskEventListener anchorListListener = new ShowToastTaskEventListener(getActivity()) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == anchorListTaskId) {
                anchorListTaskId = -1;
                if (currentPage == 1) {
                    mAdapter.clearData();
                }
                if (data != null) {
                    mList = (List<PengYouQuanInfo>) data;
                    if (mList != null && mList.size() > 0) {
                        mAdapter.updateData(mList);
                    }
                }

                currentPage = result;

            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == anchorListTaskId) {
                anchorListTaskId = -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {

        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isShow = true;
            if (mAdapter != null) {
                currentPage = 1;
                getData();
            }
        } else {
            isShow = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isShow) {
            currentPage = 1;
            getData();
        }

    }
}
